package com.sp.system.user.utils;


import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class LetterCodeUtil {

    private static HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

    public static String hanyu2pinyin(String hanzi) {
        // UPPERCASE：大写  (ZHONG)
        // LOWERCASE：小写  (zhong)
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);

        // WITHOUT_TONE：无音标  (zhong)
        // WITH_TONE_NUMBER：1-4数字表示英标  (zhong4)
        // WITH_TONE_MARK：直接用音标符（必须WITH_U_UNICODE否则异常）  (zhòng)
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        // WITH_V：用v表示ü  (nv)
        // WITH_U_AND_COLON：用"u:"表示ü  (nu:)
        // WITH_U_UNICODE：直接用ü (nü)
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        try {
            StringBuffer pinyin = new StringBuffer();
            for (int i = 0; i < hanzi.length(); i++) {
                String[] onepinyin = PinyinHelper.toHanyuPinyinStringArray(hanzi.charAt(i), format);
                if(null!=onepinyin){
                    pinyin.append(onepinyin[0].substring(0, 1));
                }
            }
            return pinyin.toString();
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static String serialNum(int length, int num) {
        String result = String.valueOf(num);
        int numLength = result.length();
        for (int i = length; i > numLength; i--) {
            result = "0" + result;
        }
        return result;
    }
}
